package com.bupt.ilink.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bupt.ilink.entity.Studyspace.DTO.SortOrderUpdateDTO;
import com.bupt.ilink.entity.Studyspace.StudyCourseFile;
import com.bupt.ilink.mapper.StudyCourseFileMapper;
import com.bupt.ilink.service.StudyCourseFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Service
public class StudyCourseFileServiceImpl implements StudyCourseFileService {

    @Autowired
    private StudyCourseFileMapper studyCourseFileMapper;

    @Override
    @Transactional
    public void updateSortOrder(SortOrderUpdateDTO dto) {
        List<Long> sortedIds = dto.getSortedIds();
        if (sortedIds == null || sortedIds.isEmpty()) {
            throw new IllegalArgumentException("排序列表不能为空");
        }

        // 查询当前父目录下所有文件，确保排序的文件属于该目录
        QueryWrapper<StudyCourseFile> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", dto.getParentId());
        queryWrapper.in("courseFile_id", sortedIds);
        List<StudyCourseFile> files = studyCourseFileMapper.selectList(queryWrapper);

        if (files.size() != sortedIds.size()) {
            throw new IllegalArgumentException("排序列表包含无效的文件 ID");
        }

        // 根据排序顺序设置 sort_order
        List<StudyCourseFile> updateList = IntStream.range(0, sortedIds.size())
                .mapToObj(index -> {
                    Long id = sortedIds.get(index);
                    StudyCourseFile file = new StudyCourseFile();
                    file.setCourseFileId(id);
                    file.setSortOrder(index + 1); // 假设 sort_order 从 1 开始
                    return file;
                })
                .collect(Collectors.toList());

        // 批量更新
        int updated = studyCourseFileMapper.updateSortOrderBatch(updateList);
        if (updated != sortedIds.size()) {
            throw new RuntimeException("更新排序顺序失败");
        }
    }
}
